﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myDNS;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace _hcmui_edu_vn_rootDNS
{
    class Program
    {

        //Hàm xử lý chính cho từng client kết nối tới server
        //public static void Progress(TcpClient ClientSocket)
        //{
        //    int level = 4;
        //    //Đối tượng nhận dữ liệu
        //    StreamReader sr = new StreamReader(ClientSocket.GetStream());

        //    Stream s = ClientSocket.GetStream();

        //    //Lặp liên tục để nhận thông điệp từ client
        //    while (true)
        //    {
        //        //Biến request để nhận thông điệp từ client
        //        string request = sr.ReadLine();
                
              
        //    if (request[0] == '0') // client send local dns server
        //        {
        //            string hostName = request.Substring(1, request.Length - 1);
        //            hostName=hostName.ToLower();

        //            string strComp = Provider.GetStringCompare(hostName, level);
        //            HostName_IP_Port resultSearch= hcmui_edu_vn_rootDNS.SearchHostName(strComp, "DNS.txt");
        //            if (resultSearch._ip == "0.0.0.0")
        //            {

        //                // gui root (server khac)
        //                DNSServer dnsServer = new DNSServer("ROOT DNS", "127.0.0.1", 100);
        //                do
        //                {
        //                    IPEndPoint iep = new IPEndPoint(IPAddress.Parse(dnsServer._ip),dnsServer._port);
        //                    TcpClient tcp = new TcpClient();
        //                    tcp.Connect(iep);
        //                    tcp.Client.Connect(iep);
        //                    tcp.Client.Send();
        //                    UdpClient u = new UdpClient();
        //                    u.Client.

        //                    StreamReader kq = tcp.GetStream();
        //                    string strKq = kq.ReadLine();

        //                    HostName_IP_Port result_ip_port = Provider.GetHostName_IP_Port(strKq);
        //                    if (result_ip_port._ip == "0.0.0.0") // no result search 
        //                    {
                               
        //                        //byte[] result = Provider.GetBytes("0.0.0.0");
        //                        ClientSocket.GetStream("0.0.0.0");
        //                        break;
        //                    }
        //                    else if (result_ip_port._ip==dnsServer._ip && result_ip_port._port==dnsServer._port) // tra ve chinh cai dns server do
        //                    {
                                
        //                        //byte[] result = Provider.GetBytes(result_ip_port._ip+result_ip_port._port.ToString());
        //                        ClientSocket.GetStream(result_ip_port._ip + result_ip_port._port.ToString());
                                
                                
        //                        break;
        //                    }
        //                    else if (result_ip_port._ip != dnsServer._ip && result_ip_port._port == 0)
        //                    {
                              
        //                        byte[] result = Provider.GetBytes(result_ip_port._ip + result_ip_port._port.ToString());
        //                        ClientSocket.GetStream(result_ip_port._ip + result_ip_port._port.ToString());
        //                        break;
        //                    }
        //                    else if (result_ip_port._ip == dnsServer._ip && result_ip_port._port != dnsServer._port)
        //                    {
                                
        //                        dnsServer._nameServer = "Temp name server";
        //                        dnsServer._ip = result_ip_port._ip;
        //                        dnsServer._port = port;

        //                    }
        //                }
        //                while (true);
                        
        //            }
        //            else
        //            {
        //                byte[] resultByte = Provider.GetBytes(resultSearch._ip);
        //               // sock = new UdpClient();
        //                ClientSocket.GetStream(resultSearch._ip);
        //                break;
                        
        //            }
        //        }
        //        else
        //        {

        //        }


                 
        //    }
        //}
        
        static void Main(string[] args)
        {
            //DNSServer hcmui_edu_vn_rootDNS = new DNSServer("HCMUI.EDU.VN.ROOT DNS ", "127.0.0.1", 107);
            //hcmui_edu_vn_rootDNS.ToString();
            //IPEndPoint iep = new IPEndPoint(IPAddress.Parse(hcmui_edu_vn_rootDNS._ip),hcmui_edu_vn_rootDNS._port);
            //TcpListener server = new TcpListener(iep);

            //TcpClient cli = new TcpClient();

            //try
            //{
            //    server.Start();
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.ToString());
            //}
            ////Lắng nghe kết nối từ client
            //while (true)
            //{
            //    TcpClient client = server.AcceptTcpClient();
            //    //Tạo đối tượng xử lý cho từng client
            //    Program p = new Program();
            //    Thread th =new Thread(new ThreadStart(p.Progress()));
                
            //    th.Start(client);
            //}






            //Socket so = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp);
            
            //// Server socket
            //Socket serverSocket;

            //// Data stream
            //byte[] dataStream = new byte[1024];

            //int level = 4;
            //DNSServer hcmui_edu_vn_rootDNS = new DNSServer("HCMUI.EDU.VN.ROOT DNS ", "127.0.0.1", 107);
            //hcmui_edu_vn_rootDNS.ToString();

            //serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //IPEndPoint server = new IPEndPoint(IPAddress.Parse(hcmui_edu_vn_rootDNS._ip),hcmui_edu_vn_rootDNS._port);
            //serverSocket.Bind(server);
            
            
            //IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
            //EndPoint epSender = (EndPoint)clients;

            //// Start listening for incoming data

            //serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

            int level = 4;
            DNSServer hcmui_edu_vn_rootDNS = new DNSServer("HCMUI.EDU.VN.ROOT DNS ", "127.0.0.1", 107);
            hcmui_edu_vn_rootDNS.ToString();

            do
            {

                UdpClient sock;
                int port = 107;
                IPEndPoint ep;
                try
                {
                    sock = new UdpClient(port);
                    ep = new IPEndPoint(0, 0);
                    byte[] recData = sock.Receive(ref ep);

                    IPEndPoint ipClient = new IPEndPoint(ep.Address, ep.Port);

                    string recString = Provider.GetString(recData);
                    //  sock.Close();

                    if (recString[0] == '0') // client send local dns server
                    {
                        string hostName = recString.Substring(1, recString.Length - 1);
                        hostName = hostName.ToLower();

                        string strComp = Provider.GetStringCompare(hostName, level);
                        HostName_IP_Port resultSearch = hcmui_edu_vn_rootDNS.SearchHostName(strComp, "DNS.txt");
                        if (resultSearch._ip == "0.0.0.0")
                        {

                            // gui root (server khac)
                            DNSServer dnsServer = new DNSServer("ROOT DNS", "127.0.0.1", 100);
                            do
                            {

                                // gui cho dns server khac (root, khac root )
                                // send ip port server
                                // receive ip port

                                //UdpClient socket = new UdpClient();
                                //sock=socket
                                UdpClient socket = new UdpClient();
                                socket.Client.Connect(dnsServer._ip, dnsServer._port);
                                //string dataSend = Provider.SendIpPort(hcmui_edu_vn_rootDNS._ip, hcmui_edu_vn_rootDNS._port, recString);
                                
                                //byte[] byteSend = Provider.GetBytes(dataSend);
                                byte[] byteSend = Provider.GetBytes(recString);
                                // socket.Send(recData, recData.Length);
                                socket.Client.Send(byteSend);

                                IPEndPoint ep1 = new IPEndPoint(0, 0);
                                EndPoint epo = (EndPoint)ep1;
                                //byte[] resultByteArray = sock.Receive(ref ep1);
                                byte[] resultByteArray = new byte[1024];
                                socket.Client.Receive(resultByteArray);
                                socket.Client.Close();

                                HostName_IP_Port result_ip_port = Provider.GetHostName_IP_Port(resultByteArray);
                                if (result_ip_port._ip == "0.0.0.0") // no result search 
                                {
                                     
                                    byte[] result = Provider.GetBytes("0.0.0.0");
                                    sock.Send(result, result.Length, ipClient);
                                    sock.Close();
                                    break;
                                }
                                else if (result_ip_port._ip == dnsServer._ip && result_ip_port._port == dnsServer._port) // tra ve chinh cai dns server do
                                {
                                    
                                    byte[] result = Provider.GetBytes(result_ip_port._ip + result_ip_port._port.ToString());
                                    sock.Send(result, result.Length, ipClient);
                                    sock.Close();
                                    break;
                                }
                                else if (result_ip_port._ip != dnsServer._ip && result_ip_port._port == 0)
                                {
                                    
                                    byte[] result = Provider.GetBytes(result_ip_port._ip + result_ip_port._port.ToString());
                                    sock.Send(result, result.Length, ipClient);
                                    sock.Close();
                                    break;
                                }
                                else if (result_ip_port._ip == dnsServer._ip && result_ip_port._port != dnsServer._port)
                                {
                                    
                                    dnsServer._nameServer = "Temp name server";
                                    dnsServer._ip = result_ip_port._ip;
                                    dnsServer._port = port;

                                }
                            }
                            while (true);

                        }
                        else
                        {
                            byte[] resultByte = Provider.GetBytes(resultSearch._ip);
                            // sock = new UdpClient();
                            sock.Send(resultByte, resultByte.Length, ipClient);
                            sock.Close();
                            break;

                        }
                    }
                    else
                    {

                    }


                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message.ToString());
                }
            }
            while (true);

        }
    }
}
